﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using My_App.Model;

namespace My_App
{
    public partial class DetailsPage : PhoneApplicationPage
    {
        public DetailsPage()
        {
            InitializeComponent();
        }

        public bool IsEdit { get; set; }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string selectedIndex = string.Empty;
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
            {
                int index = int.Parse(selectedIndex);
                DataContext = App.ViewModel.Items[index];

                if (App.ViewModel.Items[index].State == TaskState.Edit)
                {
                    IsEdit = true;
                    task_name.IsEnabled = false;
                }
            }
        }
        
        private void SaveClick(object sender, RoutedEventArgs e)
        {
            if (IsEdit)
            {
                Task task = App.ViewModel.Items.FirstOrDefault(i => i.Name == this.task_name.Text);
                if (task != null)
                {
                    task.Description = this.task_description.Text;
                    task.State = TaskState.Normal;
                }
            }
            else
            {
                string name = task_name.Text;
                string description = task_description.Text;
                Task myTask = new Task { Name = name, Description = description };
                App.ViewModel.Items.Add(myTask);
            }

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void CancelClick(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }
    }
}